package mybatis.transaction.managed;

import mybatis.session.TransactionIsolationLevel;
import mybatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

public class ManagedTransaction implements Transaction {

    private final boolean closeConnection;
    private DataSource dataSource;
    private TransactionIsolationLevel level;
    private Connection connection;

    public ManagedTransaction(Connection connection, boolean closeConnection) {
        this.connection = connection;
        this.closeConnection = closeConnection;
    }

    public ManagedTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean closeConnection) {
        this.dataSource = dataSource;
        this.level = level;
        this.closeConnection = closeConnection;
    }

    /**
     * 获取数据库链接的方法
     *
     * @return 返回数据库链接
     * @throws SQLException 获取链接失败的异常
     */
    @Override
    public Connection getConnection() throws SQLException {
        if (connection == null) {
            openConnection();
        }
        return connection;
    }

    @Override
    public void commit() {
    }

    @Override
    public void rollback() {
    }

    /**
     * 关闭数据库连接的方法
     *
     * @throws SQLException 关闭连接失败的数据库异常
     */
    @Override
    public void close() throws SQLException {
        if (closeConnection && Objects.nonNull(connection)) {
            connection.close();
        }
    }

    @SuppressWarnings({"MagicConstant"})
    protected void openConnection() throws SQLException {
        this.connection = dataSource.getConnection();
        if (level != null) {
            connection.setTransactionIsolation(level.getLevel());
        }
    }
}
